// pages/jobs/jobs.js
Page({
  data: {
    jobs: [],
    loading: false,
    hasMore: true,
    page: 0,
    size: 10,
    filters: {
      keyword: '',
      jobType: '',
      location: '',
      salaryRange: ''
    },
    showFilter: false,
    jobTypes: [
      { value: '', label: '全部类型' },
      { value: 'FULL_TIME', label: '全职' },
      { value: 'PART_TIME', label: '兼职' },
      { value: 'TEMPORARY', label: '临时工' },
      { value: 'INTERNSHIP', label: '实习' }
    ],
    locations: [
      { value: '', label: '全部地区' },
      { value: '北京', label: '北京' },
      { value: '上海', label: '上海' },
      { value: '广州', label: '广州' },
      { value: '深圳', label: '深圳' },
      { value: '杭州', label: '杭州' }
    ],
    salaryRanges: [
      { value: '', label: '不限薪资' },
      { value: '0-3000', label: '3000以下' },
      { value: '3000-5000', label: '3000-5000' },
      { value: '5000-8000', label: '5000-8000' },
      { value: '8000-12000', label: '8000-12000' },
      { value: '12000-20000', label: '12000-20000' },
      { value: '20000+', label: '20000以上' }
    ]
  },

  onLoad() {
    this.loadJobs(true);
  },

  onShow() {
    // 如果从详情页返回，刷新列表
    if (this.data.jobs.length > 0) {
      this.loadJobs(true);
    }
  },

  // 加载岗位列表
  loadJobs(refresh = false) {
    if (this.data.loading) return;

    this.setData({ loading: true });

    const page = refresh ? 0 : this.data.page;
    const token = wx.getStorageSync('token');

    wx.request({
      url: 'http://localhost:8080/api/jobs',
      method: 'GET',
      header: token ? { 'Authorization': `Bearer ${token}` } : {},
      data: {
        page: page,
        size: this.data.size,
        keyword: this.data.filters.keyword,
        jobType: this.data.filters.jobType,
        location: this.data.filters.location,
        salaryRange: this.data.filters.salaryRange
      },
      success: (res) => {
        if (res.data.code === 200) {
          const newJobs = (res.data.data.content || []).map(job => ({
            ...job,
            // 用工者信息脱敏处理
            employerName: this.maskEmployerName(job.employerName || job.employer?.companyName),
            company: this.maskEmployerName(job.employerName || job.employer?.companyName)
          }));
          this.setData({
            jobs: refresh ? newJobs : [...this.data.jobs, ...newJobs],
            hasMore: !res.data.data.last,
            page: page + 1
          });
        }
      },
      fail: () => {
        // 模拟数据
        const mockJobs = [
          {
            id: 1,
            title: '前端开发工程师',
            company: '某科技公司',
            jobType: 'FULL_TIME',
            minSalary: 8000,
            maxSalary: 15000,
            salaryType: 'MONTHLY',
            location: '北京市朝阳区',
            description: '负责公司前端项目开发，要求熟悉React、Vue等框架',
            requiredWorkers: 2,
            matchedWorkers: 1,
            publishTime: '2024-01-10 10:00:00'
          },
          {
            id: 2,
            title: '服务员',
            company: '某餐饮公司',
            jobType: 'PART_TIME',
            minSalary: 20,
            maxSalary: 25,
            salaryType: 'HOURLY',
            location: '上海市浦东新区',
            description: '负责餐厅日常服务工作，要求有相关经验',
            requiredWorkers: 5,
            matchedWorkers: 3,
            publishTime: '2024-01-09 14:30:00'
          },
          {
            id: 3,
            title: '快递员',
            company: '某物流公司',
            jobType: 'FULL_TIME',
            minSalary: 150,
            maxSalary: 200,
            salaryType: 'DAILY',
            location: '广州市天河区',
            description: '负责快递配送工作，要求熟悉本地路况',
            requiredWorkers: 10,
            matchedWorkers: 8,
            publishTime: '2024-01-08 09:15:00'
          }
        ];

        this.setData({
          jobs: refresh ? mockJobs : [...this.data.jobs, ...mockJobs],
          hasMore: false,
          page: page + 1
        });
      },
      complete: () => {
        this.setData({ loading: false });
        if (refresh) {
          wx.stopPullDownRefresh();
        }
      }
    });
  },

  // 搜索岗位
  onSearchInput(e) {
    this.setData({
      'filters.keyword': e.detail.value
    });
  },

  onSearchConfirm() {
    this.loadJobs(true);
  },

  // 显示/隐藏筛选器
  toggleFilter() {
    this.setData({
      showFilter: !this.data.showFilter
    });
  },

  // 筛选条件改变
  onFilterChange(e) {
    const { type } = e.currentTarget.dataset;
    const value = e.detail.value;
    
    this.setData({
      [`filters.${type}`]: value
    });
  },

  // 应用筛选
  applyFilter() {
    this.setData({ showFilter: false });
    this.loadJobs(true);
  },

  // 重置筛选
  resetFilter() {
    this.setData({
      filters: {
        keyword: '',
        jobType: '',
        location: '',
        salaryRange: ''
      }
    });
    this.loadJobs(true);
  },

  // 跳转到岗位详情
  goToJobDetail(e) {
    const jobId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/job-detail/job-detail?id=${jobId}`
    });
  },

  // 格式化薪资显示
  formatSalary(job) {
    const { minSalary, maxSalary, salaryType } = job;
    let unit = '';
    switch (salaryType) {
      case 'HOURLY': unit = '/时'; break;
      case 'DAILY': unit = '/天'; break;
      case 'MONTHLY': unit = '/月'; break;
      default: unit = '';
    }
    
    if (minSalary === maxSalary) {
      return `${minSalary}元${unit}`;
    }
    return `${minSalary}-${maxSalary}元${unit}`;
  },

  // 格式化岗位类型
  formatJobType(type) {
    const typeMap = {
      'FULL_TIME': '全职',
      'PART_TIME': '兼职',
      'TEMPORARY': '临时工',
      'INTERNSHIP': '实习'
    };
    return typeMap[type] || type;
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadJobs(true);
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadJobs(false);
    }
  },

  // 用工者名称脱敏处理
  maskEmployerName(name) {
    if (!name) return '***公司';
    if (name.length <= 2) {
      return name.charAt(0) + '*';
    } else if (name.length <= 4) {
      return name.charAt(0) + '*'.repeat(name.length - 2) + name.charAt(name.length - 1);
    } else {
      return name.substring(0, 2) + '*'.repeat(name.length - 4) + name.substring(name.length - 2);
    }
  }
});
